package com.oj.judge.codesandbox.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.oj.judge.codesandbox.CodeSandBox;
import com.oj.judge.domain.ExecuteCodeRequest;
import com.oj.judge.domain.ExecuteCodeResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class RemoteCodeSandBox implements CodeSandBox {

    private static final String URL = "http://203.195.71.233:8092/executeCode";

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        try {
            String jsonStr = JSONUtil.toJsonStr(executeCodeRequest);
            HttpResponse httpResponse = HttpUtil.createPost(URL)
                    .body(jsonStr)
                    .execute();

            if (httpResponse.isOk()) {
                String responseStr = httpResponse.body();
                log.info("responseStr: {}", responseStr);
                return JSONUtil.toBean(responseStr, ExecuteCodeResponse.class);
            } else {
                log.error("执行代码请求失败，状态码：{}", httpResponse.getStatus());
                ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
                executeCodeResponse.setStatus(String.valueOf(httpResponse.getStatus()));
                executeCodeResponse.setMessage("执行代码请求失败");
                return executeCodeResponse;
            }
        } catch (Exception e) {
            log.error("执行代码时发生异常", e);
            ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
            executeCodeResponse.setStatus("500");
            executeCodeResponse.setMessage("执行代码请求失败");
            return executeCodeResponse;
        }
    }
}
